//
//  ImageViewController.swift
//  GifUsage
//
//  Created by han on 2020/12/29.
//  Copyright © 2020 Ting Han. All rights reserved.
//

import UIKit
import Photos

class ImageViewController: UIViewController {
    
    var image: UIImage? {
        didSet {
            guard let image = image else { return }
            imageView.image = image
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        commonInit()
    }
    
    let activityIndicator = UIActivityIndicatorView(style: .large)
    
    private var currentScale: CGFloat = 1.0
    
    lazy var imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    lazy  var scrollView: UIScrollView = {
        let scrollView = UIScrollView(frame: view.bounds)
        scrollView.contentSize = view.bounds.size
        scrollView.delegate = self
        scrollView.minimumZoomScale = 1
        scrollView.maximumZoomScale = 4
        return scrollView
    }()
}

extension ImageViewController {
    private func commonInit() {
        setupNavigationBar()
        setupSubviews()
    }
    
    private func setupNavigationBar() {
        navigationItem.title = "Images"
        view.backgroundColor = .black
       let right = UIBarButtonItem(title: "保存", style: .done, target: self, action: #selector(saveAction))
        navigationItem.rightBarButtonItem = right
    }
    
    @objc func saveAction() {
        guard let image = image else { return }
        activityIndicator.startAnimating()
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }, completionHandler: {success, error in
            if !success { print("error creating asset: \(String(describing: error))") }
            DispatchQueue.main.async {
                self.activityIndicator.stopAnimating()
                showTips(self, success ? "保存成功" : "保存失败", success ? "" : "error creating asset: \(String(describing: error))")
            }
        })
    }
    
    private func setupSubviews() {
        view.addSubview(scrollView)
        scrollView.addSubview(imageView)
        let size = CGSize(width: scrollView.bounds.width, height: scrollView.bounds.height - navigationBarHeight)
        imageView.frame = CGRect(origin: .zero, size: size)
        imageView.image = image
        scrollView.contentSize = size
        
        view.addSubview(activityIndicator)
        activityIndicator.center = CGPoint(x: view.frame.midX, y: view.frame.midY)
        
        let doubleTap = UITapGestureRecognizer(target: self, action: #selector(doubleTapAction(_:)))
        doubleTap.numberOfTapsRequired = 2
        scrollView.addGestureRecognizer(doubleTap)
    }
    
    @objc func doubleTapAction(_ tap: UITapGestureRecognizer) {
        let center = tap.location(in: tap.view)
        if currentScale != 1 {
            setZoomScale(1, scrollView.center)
        } else {
            setZoomScale(currentScale * 2, center)
        }
    }
    
    func zoomRect(scale: CGFloat, center: CGPoint) -> CGRect {
        var zoomRect: CGRect = .zero
        zoomRect.size.height = scrollView.frame.height / scale
        zoomRect.size.width  = scrollView.frame.width  / scale;
        zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
        zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
        return zoomRect
    }
    
    
    func setZoomScale(_ scale: CGFloat, _ center: CGPoint) {
        currentScale = scale
//        scrollView.zoomScale = currentScale
        let rect = zoomRect(scale: currentScale, center: center)
        scrollView.zoom(to: rect, animated: true)
    }
    
    var navigationBarHeight: CGFloat {
        return navigationController?.navigationBar.frame.height ?? 0 + statusBarHeight
    }
    
    var statusBarHeight: CGFloat {
        if #available(iOS 13, *) {
               return UIApplication.shared.windows.first?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0
           } else {
               return UIApplication.shared.statusBarFrame.height
           }
    }
}

extension ImageViewController: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return imageView
    }
    
    func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
        currentScale = scale
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
    }
}
